package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.filter.IFilterConfig;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserLoginRequest;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.dto.UserVerifyResponse;
import com.cskaoyan.user.service.ILoginService;
import com.google.common.base.Verify;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * ClassName: IloginServiceImpl
 * Description:
 * date: 2022/6/18 21:02
 *
 * @author bruce
 * @since JDK 8
 */
@Service
@Slf4j
public class IloginServiceImpl implements ILoginService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Override
    public UserLoginResponse login(UserLoginRequest loginRequest) {
        UserLoginResponse response = new UserLoginResponse();
        //判空验证
        loginRequest.requestCheck();

        //查询数据库中是否有对应的账号密码
        Example example = new Example(Member.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username", loginRequest.getUserName());
        String pwd = DigestUtils.md5DigestAsHex(loginRequest.getPassword().getBytes());
        criteria.andEqualTo("password", pwd);
        List<Member> members = memberMapper.selectByExample(example);
        if (members.size() != 1) {
            //登录失败
            response.setCode(UserRetCode.USERORPASSWORD_ERRROR.getCode());
            response.setMsg(UserRetCode.USERORPASSWORD_ERRROR.getMessage());
            return response;
        }
        if ("N".equals(members.get(0).getIsVerified())) {
            //用户未激活
            response.setCode(UserRetCode.USER_ISVERFIED_ERROR.getCode());
            response.setMsg(UserRetCode.USER_ISVERFIED_ERROR.getMessage());
            return response;
        }
        //打印日志
        log.info("用户登录成功，登录参数request：{}", JSON.toJSONString(loginRequest));
        //登陆成功
        response.setCode(UserRetCode.SUCCESS.getCode());
        response.setMsg(UserRetCode.SUCCESS.getMessage());
        response.setId(members.get(0).getId());
        response.setUsername(members.get(0).getUsername());
        response.setFile(members.get(0).getFile());
        response.setState(members.get(0).getState());
        return response;
    }
}
